package com.andy.app_core.net.download;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;

import com.andy.app_core.ProjectInit;
import com.andy.app_core.net.callback.IRequest;
import com.andy.app_core.net.callback.ISuccess;
import com.andy.app_core.net.utils.file.FileUtil;

import java.io.File;
import java.io.InputStream;

import okhttp3.ResponseBody;

/**
 * @version V1.0
 * @描述: 保存文件
 * @Company:
 * @auth: Created by AN .
 * @time: 2020/3/26 22:22
 * @des
 */
public class SaveFileTask extends AsyncTask<Object,Void,File> {
    private final IRequest REQUEST;
    private final ISuccess SUCCESS;

    public SaveFileTask(IRequest REQUEST, ISuccess SUCCESS) {
        this.REQUEST = REQUEST;
        this.SUCCESS = SUCCESS;
    }

    @Override
    protected File doInBackground(Object... params) {
        String downloadDirs= (String) params[0];
        String extension= (String) params[1];
        ResponseBody body= (ResponseBody) params[2];
        String name = (String) params[3];

        InputStream is=body.byteStream();
        if(downloadDirs ==null ||downloadDirs.equals("")){
            downloadDirs="download";
        }
        if(extension ==null){
            extension="";
        }
        if(name ==null){
            return FileUtil.writeToDisk(is,downloadDirs,extension.toUpperCase(),extension);
        }else{
            return FileUtil.writeToDisk(is,downloadDirs,name);
        }

    }

    //文件下载完
    @Override
    protected void onPostExecute(File file) {
        super.onPostExecute(file);
        if(SUCCESS !=null){
            SUCCESS.onSuccess(file.getPath());
        }
        if(REQUEST != null){
            REQUEST.onRequestEnd();
        }
        autoInstallApk(file);
    }

    private void autoInstallApk(File file) {
        if(FileUtil.getExtension(file.getPath()).equals("apk")){
            final Intent intent=new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file),"appliacation/vnd.android.package-archive");
            ProjectInit.getApplicationContext().startActivity(intent);
        }
    }
}
